<template>
  <div class="notification-management">
    <el-card>
      <div class="card-header">
        <h2>公告通知管理</h2>
        <el-button type="primary" @click="openAddDialog">添加公告</el-button>
      </div>

      <el-table :data="notifications" style="width: 100%">
        <el-table-column prop="notificationId" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="标题" width="200"></el-table-column>
        <el-table-column prop="content" label="内容" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="typeMap[scope.row.type].type">
              {{ typeMap[scope.row.type].label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="viewNotification(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteNotification(scope.row.notificationId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          style="margin-top: 20px; text-align: right"
      ></el-pagination>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" maxlength="100"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" rows="6"></el-input>
        </el-form-item>
        <div class="form-group">
          <label>上传图片</label>
          <input type="file" ref="fileInput" @change="handleFileUpload" accept="image/*" multiple>
          <div v-if="uploadProgress > 0" class="upload-progress">
            <div class="progress-bar" :style="{ width: uploadProgress + '%' }"></div>
            <span>{{ uploadProgress }}%</span>
          </div>
          <div v-if="uploadedImageUrls.length > 0" class="uploaded-images">
            <div v-for="(url, index) in uploadedImageUrls" :key="index" class="image-preview">
              <img :src="url" alt="图片" @error="handleImageError">
              <button @click="removeImage(index)" class="remove-image-btn">×</button>
            </div>
          </div>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="公告详情" width="600px">
      <div v-if="currentNotification" class="notification-detail">
        <h3>{{ currentNotification.title }}</h3>
        <div class="detail-meta">
          <span>类型：{{ typeMap[currentNotification.type].label }}</span>
          <span>创建时间：{{ currentNotification.createdAt }}</span>
        </div>
        <div class="detail-content" v-html="currentNotification.content"></div>
        <div v-if="currentNotification.relatedId" class="detail-related">
          <strong>相关ID：</strong>{{ currentNotification.relatedId }}
        </div>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import axios from '@/utils/axios'
import OSS from "ali-oss";

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json'
  }
});

// 状态管理
const notifications = ref([]);
const currentPage = ref();
const pageSize = ref(10);
const total = ref();
const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const dialogTitle = ref('添加公告');
const currentNotification = ref(null);
let formRef = ref(null);
let uploadedImageUrls = ref([]); // 存储所有上传成功的图片 URL
const uploadProgress = ref(0);     // 上传进度
const fileInput = '';
// 表单数据
const form = reactive({
  notificationId: null,
  title: '',
  content: '',
  images:'',
  type: '',
  relatedId: null
});

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { max: 100, message: '标题不能超过100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择通知类型', trigger: 'change' }
  ]
};

// 类型映射
const typeMap = {
  1: { label: '系统通知', type: 'info' },
};

// 获取通知列表
const fetchNotifications = async () => {
  try {
    const response = await api.get('/admin/notifications', {
      params: { page: currentPage.value, size: pageSize.value }
    });
    console.log(response.data)
    notifications.value = response.data.notifications;
    total.value = response.data.totalElements;
  } catch (error) {
    ElMessage.error('获取通知列表失败');
    console.error(error);
  }
};

// 分页变化处理
const handleCurrentChange = (page) => {
  currentPage.value = page - 1; // 转换为0-based索引
  fetchNotifications();
};

// 打开添加对话框
const openAddDialog = () => {
  dialogTitle.value = '添加公告';
  form.notificationId = null;
  form.title = '';
  form.content = '';
  form.images='';
  form.type = '';
  form.relatedId = null;
  uploadedImageUrls.value = [];
  formRef.value = []
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (notification) => {
  dialogTitle.value = '编辑公告';
  form.notificationId = notification.notificationId;
  form.title = notification.title;
  form.content = notification.content;
  form.type = notification.type.toString();
  form.relatedId = notification.relatedId;
  dialogVisible.value = true;
};

// 查看通知详情
const viewNotification = (notification) => {
  currentNotification.value = notification;
  viewDialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (form.notificationId) {
      // 更新操作
      await api.put(`/admin/notifications/${form.notificationId}`, form);
      ElMessage.success('公告更新成功');
    } else {
      // 添加操作
      await api.post('/admin/notifications', form);
      ElMessage.success('公告添加成功');
    }

    dialogVisible.value = false;
    fetchNotifications();
  } catch (error) {
    if (error.name === 'ValidationError') return;
    ElMessage.error(form.notificationId ? '更新失败' : '添加失败');
    console.error(error);
  }
  form.notificationId = null;
  form.title = '';
  form.content = '';
  form.images='',
  form.type = '';
  form.relatedId = null;
  uploadedImageUrls= [];
  formRef.value = []
  if (this.$refs.fileInput) {
    this.$refs.fileInput.value = '';
  }
};

// 删除通知
const deleteNotification = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条公告吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await api.delete(`/admin/notifications/${id}`);
    ElMessage.success('删除成功');
    fetchNotifications();
  } catch (error) {
    if (error === 'cancel') return;
    ElMessage.error('删除失败');
    console.error(error);
  }
};

// 状态管理


// 文件上传处理函数
const handleFileUpload = async (event) => {
  const files = event.target.files;
  if (!files || files.length === 0) return;

  uploadProgress.value = 10;

  try {
    const uploadPromises = Array.from(files).map(async (file) => {
      // 文件类型验证
      if (!file.type.match('image.*')) {
        alert('请选择图片文件');
        return null;
      }

      // 文件大小验证
      if (file.size > 5 * 1024 * 1024) {
        alert('图片大小不能超过5MB');
        return null;
      }

      try {
        uploadProgress.value = 30;

        const client = new OSS({
          endpoint: 'oss-cn-hangzhou.aliyuncs.com',
          accessKeyId: 'LTAI5tJQmVkAX4LzgqYwdUFN',
          accessKeySecret: '2f26fXcpc1utxlR0hSbvbJRbeIf4hE',
          bucket: 'yangodofsc',
        });

        const fileName = `images/${Date.now()}_${file.name}`;

        const result = await client.put(fileName, file, {
          progress: (p) => {
            uploadProgress.value = Math.round(p * 100);
          }
        });

        return result.url;
      } catch (error) {
        console.error('上传失败:', error);
        alert('图片上传失败');
        return null;
      }
    });

    // 等待所有文件上传完成
    const results = await Promise.all(uploadPromises);
    const newUrls = results.filter(url => url !== null);

    // 更新图片 URL 数组
    uploadedImageUrls.value = [...uploadedImageUrls.value, ...newUrls];

    // 将图片 URL 数组转换为字符串并存入表单
    form.images = JSON.stringify(uploadedImageUrls.value); // 使用逗号分隔

    uploadProgress.value = 100;

    setTimeout(() => {
      uploadProgress.value = 0;
    }, 1000);

  } catch (error) {
    console.error('上传处理失败:', error);
    uploadProgress.value = 0;
  }
};

// 图片加载失败处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event);
  event.target.style.display = 'none';
};

// 删除图片
const removeImage = (index) => {
  uploadedImageUrls.value.splice(index, 1);

  // 更新表单中的图片字段
  form.images = JSON.stringify(uploadedImageUrls.value);
};
// 页面加载时获取数据
onMounted(() => {
  fetchNotifications();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.notification-detail {
  padding: 10px 0;
}

.notification-detail h3 {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.detail-meta {
  margin-bottom: 15px;
  color: #666;
  display: flex;
  gap: 20px;
}

.detail-content {
  line-height: 1.6;
  margin-bottom: 20px;
  min-height: 100px;
}

.detail-related {
  color: #666;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
/* 模态框内的表单样式 */
.form-group {
  margin-bottom: 15px;
}
.form-group label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
}
.form-group input,
.form-group select {
  width: 95%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.uploaded-images {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  flex-wrap: wrap;
}

.image-preview {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.remove-image-btn {
  position: absolute;
  top: 2px;
  right: 2px;
  background: #ff4444;
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  cursor: pointer;
  font-size: 12px;
  line-height: 1;
}

.upload-progress {
  margin-top: 10px;
  height: 20px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.progress-bar {
  height: 100%;
  background: #007bff;
  transition: width 0.3s;
}

.upload-progress span {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  text-align: center;
  line-height: 20px;
  color: white;
  font-size: 12px;
}
</style>